package com.dragon.repository.mapper;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dragon.repository.config.annotation.DataScope;
import com.dragon.repository.entity.PurchaseRequisition;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

/**
 * <p>
 * 请购单 Mapper 接口
 * </p>
 *
 * @author sy
 * @since 2023-10-20
 */
@Mapper
public interface PurchaseRequisitionMapper extends BaseMapper<PurchaseRequisition> {

    @Select("<script>" +
            "SELECT M.* FROM (select a.*, aa.username as adminName, ab.name as departmentName from dragon_purchase_requisition a " +
            "left join dragon_admin aa on a.admin_id = aa.id " +
            "left join dragon_department ab on a.department_id = ab.id) M WHERE 1=1 " +
            "<if test='id != null and id != \"\"'> "+
            " and M.id = #{id} " +
            "</if> " +
            "<if test='search != null and search != \"\"'> "+
            " and M.title like CONCAT('%',#{search},'%')  " +
            "</if> " +
            "ORDER BY M.create_time DESC " +
            "</script>")
    @DataScope(adminField = "admin_id, operator_id", deptField = "department_id", authCodeString = "purchaseRequest")
    Page<PurchaseRequisition> selectPurchasePage(Page<PurchaseRequisition> prPage, Integer id, String search);

    @Select("SELECT MAX(purchase_code) FROM dragon_purchase_requisition WHERE purchase_code LIKE CONCAT(#{code},'%')")
    String maxRoundInoutNumber(String code);



    @Select("SELECT M.* FROM (select a.*, aa.username as adminName, ab.name as departmentName from dragon_purchase_requisition a " +
            "left join dragon_admin aa on a.admin_id = aa.id " +
            "left join dragon_department ab on a.department_id = ab.id) M WHERE 1=1 AND M.id = #{purchaseId} " )
    PurchaseRequisition selectDetailById(Integer purchaseId);

    @Select("SELECT a.* FROM dragon_purchase_requisition a " +
            "LEFT JOIN dragon_requisition_product aa on aa.requisition_id = a.id " +
            "LEFT JOIN dragon_procurement_product aaa on aaa.requisition_product_id = aa.id WHERE aaa.id = #{id}")
    PurchaseRequisition selectByProcurementProductId(Integer id);
}
